package com.tjetc.service.impl;

import com.tjetc.common.JsonResult;
import com.tjetc.dao.FavouriteMapper;
import com.tjetc.dao.UserMapper;
import com.tjetc.entity.User;
import com.tjetc.service.LikesService;
import com.tjetc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    FavouriteMapper favouriteMapper;

    @Override
    public JsonResult register(String username, String password, String phone) {
        User existingUser = userMapper.findByUsername(username);
        if (existingUser != null) {
            return JsonResult.fail("用户名已存在，请选择其他用户名");
        }

        User user = new User();
        user.setUserName(username);
        user.setPassword(password);
        user.setStatus(3L);
        user.setExp(0L);
        user.setPhone(phone);
        int result = userMapper.insert(user);
        favouriteMapper.insertDefaultFolders(user.getUserId());
        if (result > 0) {
            return JsonResult.success("注册成功，请登录", user);
        } else {
            return JsonResult.fail("注册失败，请稍后重试");
        }
    }

    @Override
    public JsonResult login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return JsonResult.fail("用户名不存在");
        }
        if (!user.getPassword().equals(password)) {
            return JsonResult.fail("密码错误");
        }


        return JsonResult.success("登录成功", user);
    }

    @Override
    public JsonResult updateUserInfo(User user) {
        // 确保 ID 存在
        if (user.getUserId() == null) {
            return JsonResult.fail("用户ID不能为空");
        }

        // 查询数据库，确保用户存在
        User existingUser = userMapper.selectById(user.getUserId());
        if (existingUser == null) {
            return JsonResult.fail("用户不存在");
        }


        int result = userMapper.updateById(user);
        if (result > 0) {
            return JsonResult.success("用户信息更新成功", user);
        } else {
            return JsonResult.fail("用户信息更新失败");
        }
    }

    @Override
    public JsonResult getUserById(Long userId) {
        User user = userMapper.selectById(userId); // 如果你用的是 MyBatis Plus
        // 或者 userMapper.findById(userId); 如果你自定义的 Mapper 方法是这个

        if (user != null) {
            return JsonResult.success(user);
        } else {
            return JsonResult.success("未找到该用户",-1);
        }
    }
    @Override
    public JsonResult gainExperience(long increaseEXP,String username){
        int suc = userMapper.gainExperience(increaseEXP,username);
        if(suc>0){
            return JsonResult.success("用户 "+username+" 经验值增加 "+increaseEXP);
        }
        else{
            return JsonResult.success("增加失败",-1);
        }
    }
}